<?php

namespace app\api\controller;

use api\channel\coupon\JingChongHandler;
use api\channel\coupon\notify\JingChong;
use api\channel\coupon\YiQiDaHandler;
use api\channel\jutuike\AroundUnion;
use api\coupon\Jiaofei100;
use app\common\model\WxpayV2;
use app\common\service\around\JtkAroundService;
use app\event\JuituikeAroundOrderNotify;
use app\event\SupplierNotifyFail;
use app\event\SupplierNotifySuccess;
use app\model\BaseSupplier;
use app\model\CouponOrder;
use app\model\CouponProductChannel;
use app\model\GoodsNotify;
use think\facade\Db;
use think\facade\Log;
use think\Request;

class NotifyV2 extends \app\BaseController
{
    /**
     * 微信支付回调.
     */
    public function wxpayNotify($agentId = 0, $type = 'wechat', $product = 'mobile')
    {
        $pay = new WxpayV2($agentId, $type, $product);

        return $pay->handlePaidNotify($product);
    }

    /**
     * 微信同步回调.
     */
    public function returnUrl()
    {
        $channel = input('channel', '');
        $url = Request::domain() . '/h5/?channel=' . $channel;

        return redirect($url);
    }

    /**
     * 守兔影票回调.
     */
    public function taototo()
    {
        $params = input('post.');
        Db::name('taototo_order_notify')
            ->insert([
                'order_id' => $params['thirdOrderId'] ?? '',
                'params' => json_encode($params, JSON_UNESCAPED_UNICODE),
            ]);
        try {
            $taototo = new \app\common\service\Taototo();

            return $taototo->notify($params);
        } catch (\Exception $e) {
            return json([
                'success' => false,
                'message' => '请求失败',
                'code' => 2048,
            ]);
        }
    }

    /**
     * 美团回调.
     *
     * http://jj.dmjvip.com/api/notify_v2/meituanNotify
     */
    public function meituanNotify()
    {
        $data = file_get_contents('php://input');
        Db::name('meituan_notify')
            ->insert([
                'data' => $data,
            ]);
        $data = json_decode($data, true);
        if (empty($data['orderid'])) {

            echo '{"errcode":"1","errmsg":"err"}';
            exit;
        }

        $profit = 0;
        if (!empty($data['ratio'])) {
            $profit = yuan2fen($data['payPrice'] * $data['ratio']);
        }
        $sid = explode('s', $data['sid']);
        $order = [
            'agent_id' => $sid[1] ?? 0,
            'channel_id' => $sid[2] ?? 0,
            'order_type' => TAKEOUT_ORDER_MEITUAN,
            'order_id' => $data['orderid'],
            'paytime' => $data['paytime'] ?? 0, // 支付时间
            'ordertime' => $data['ordertime'] ?? 0, // 下单时间
            'payprice' => yuan2fen($data['payPrice']),
            'profit' => $profit,
            'sid' => $data['sid'],
            'user_id' => $sid[0] ?? 0,
            'title' => $data['smstitle'],
            'status' => $data['status'],
            'extra' => json_encode($data, JSON_UNESCAPED_UNICODE),
            'img' => '//jj.dmjvip.com/static/images/mt.png',
            'sub_order_type' => $data['businessLine'],
        ];
        $check = Db::name('takeout_order')
            ->where('order_type', TAKEOUT_ORDER_MEITUAN)
            ->where('order_id', $data['orderid'])
            ->find();
        if (empty($check)) {
            Db::name('takeout_order')->insert($order);
        } else {
            if (1 == $check['status'] && $check['status'] != $data['status']) {
                Db::name('takeout_order')
                    ->where('id', $check['id'])
                    ->update($order);
            }
        }
        echo '{"errcode":"0","errmsg":"ok"}';
    }

    /**
     *  权益订单回调.
     */
    public function coupon()
    {
        $data = input();
        $outId = $data['OutID'] ?? '';
        if (isset($data['OutID']) && isset($data['State'])) {
            $cardInfo = $data['OrderInfo'] ?? [];
            $couponOrder = new CouponOrder();
            $couponOrder->orderBack($data['OutID'], $data['State'], $cardInfo);
        }
        GoodsNotify::addGoods($data, [], $outId, 2);
        return 'success';
    }

    /**
     * 缴费100 订单回调
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function jiaofeiCouponNotify()
    {
        $baseSupplier = BaseSupplier::where(['code' => 'jiaofei100'])
            ->whereNull('deleted_at')
            ->find();
        if (empty($baseSupplier)) {
            echo '账号异常';
            exit;
        }
        $data = input();
        $model = new Jiaofei100($baseSupplier);
        echo $model->notify($data);
    }

    /**
     * 亿奇达订单状态回调.
     * @author ymzhang
     * @date 2022-07-01
     * @time 17:00
     */
    public function yiqidaNotify(Request $request)
    {
        $supplierId = $request->param('supplierId');
        $info = BaseSupplier::find($supplierId);
        $params = file_get_contents('php://input');
        $sign = $request->param('sign');
        $data = json_decode($params, true);
        //Log::info($sign);
        if (empty($info)) {
            $mark = web_request([], false, 506, '供应商账号异常，请联系商务');
            $notify = new \app\model\Notify([
                'params' => $data,
                'from' => '亿奇达',
                'relation_no' => $data['externalOrderno'],
                'mark' => $mark,
            ]);
            $notify->save();
            return $mark;
        }
        $handler = new YiQiDaHandler();
        $res = $handler->sycNotify($sign, $params);
        if (!($res['status'] && $res['code'] == 200)) {
            $mark = web_request([], false, 506, '参数错误或者签名验证失败');
            $notify = new \app\model\Notify([
                'params' => $data,
                'from' => '亿奇达',
                'relation_no' => $data['externalOrderno'],
                'mark' => $mark,
            ]);
            $notify->save();
            return $mark;
        }
        //亿奇达状态
        //status==1	等待支付，下一时刻会变成2
        //status==2	等待发货，等待处理
        //status==3	已发货，物流派送中
        //status==4	交易成功，订单完成，虚拟充值商品订单成功为该状态
        //status==5	交易取消，订单失败，虚拟充值商品订单失败为该状态
        //status==6	处理中，正在处理
        if ($data['status'] == YiQiDaHandler::ORDER_STATUS_SUCCESS) { //对接成功
            $status = CouponOrder::C_STATUS_RECHARGE_SUCCESS;
        } else if ($data['status'] == YiQiDaHandler::ORDER_STATUS_CANCEL) { //充值失败
            $status = CouponOrder::C_STATUS_RECHARGE_FAIL;
        } else { //订单处理中
            $notify = new \app\model\Notify([
                'params' => $data,
                'from' => '亿奇达',
                'relation_no' => $data['externalOrderno'],
                'mark' => ['msg' => '订单处理中'],
            ]);
            $notify->save();
            return false;
        }
        //系统状态
        //0未提交 1已提交  2提交失败 3充值成功  4充值失败 5订单处理中 10超时关闭
        //查询couponOrder对象
        /** @var CouponOrder $couponOrder */
        $couponOrder = CouponOrder::query()->where('order_id', $data['externalOrderno'])->find();

        $couponOrder->supplier_order_sn = $data['orderNo'];

        if ($status == CouponOrder::C_STATUS_RECHARGE_SUCCESS) {
            //支付成功事件
            event(new SupplierNotifySuccess($couponOrder));
            $msg = '支付成功';
        } else { //失败
            //支付失败事件
            event(new SupplierNotifyFail($couponOrder));
            $msg = '支付失败';
        }
        $notify = new \app\model\Notify([
            'params' => $data,
            'from' => '亿奇达',
            'relation_no' => $data['externalOrderno'],
            'mark' => ['msg' => $msg],
        ]);
        $notify->save();
        //记录日志
        Log::info($data);
        //记录回调日志
        return 'ok';
        //die('ok');
    }

    /**
     * 聚推客周边游 下单回调
     * /api/notifyV2/jutuikeAroundNotify
     * @param Request $request
     * @return array|bool|string
     */
    public function jutuikeAroundNotify(Request $request) {
        $tip = 'SUCCESS';
        Log::info('=====聚推客周边游回调开始下单=====');
        if (isProd() || isTesting()) {
            $params = file_get_contents('php://input');
            $data = json_decode($params, true);
            if (empty($data) && config('app.ju_tui_ke_refund')) {
                $data = $request->param();
            }
        } else {
            $data = $request->param();
        }

        // 记录日志
        Log::info('聚推客周边游下单回调' . json_encode($data));


        $orderId = $data['thirdPartyOrderNo'] ?? '';
        $couponOrder = CouponOrder::where('order_id', $orderId)->find();


        if (empty($couponOrder)) {
            $msg = '订单不存在';
            $notify = new \app\model\Notify([
                'params' => $data,
                'from' => '聚推客周边游',
                'relation_no' => $orderId,
                'mark' => $msg,
            ]);
            $notify->save();

            return 'fail';
        }

        $callType = '发码回调';
        if (isset($data['checkTime']) && isset($data['orderId'])) {
            // 核销回调 -- 供应商成功
            $checkTime = $data['checkTime'];
            $checkOrderId = $data['orderId'];
            $extData = $couponOrder->ext_data ?? [];
            $extData[JtkAroundService::ORDER_NOTIFY_CHECK][$checkOrderId] = $data;
            $couponOrder->ext_data = $extData;

            $couponOrder->order_finish_at = $checkTime; // 核销时间 就是完成时间
            $callType = '核销回调';
            event(new SupplierNotifySuccess($couponOrder, $data));

        } else if (isset($data['orderAllPrice']) && isset($data['refundDate'])) {
            $orderAllPrice = $data['orderAllPrice'];
            if ($orderAllPrice > 0) {
                $extData = $couponOrder->ext_data ?? [];
                $extData[JtkAroundService::ORDER_NOTIFY_REFUND] = $data;
                $couponOrder->ext_data = $extData;
                $couponOrder->refund_amount = $orderAllPrice;
                $callType = '退款回调';
                event(new SupplierNotifyFail($couponOrder, $data));
            }
        } else {
            // 发码回调
            $extData = $couponOrder->ext_data ?? [];
            $extData[JtkAroundService::ORDER_NOTIFY_SEND] = $data;
            $couponOrder->ext_data = $extData;
            if (isset($data['channelOrderId'])) {
                $couponOrder->supplier_order_sn = $data['channelOrderId'];
            }
            $couponOrder->save();
        }


        $notify = new \app\model\Notify([
            'params' => $data,
            'from' => '聚推客周边游-' . $callType,
            'relation_no' => $data['thirdPartyOrderNo'] ?? '',
            'mark' => '下单回调成功',
        ]);
        $notify->save();


        return $tip;  // 暂时注释，测试通过后在开启

    }

    /**
     * 鲸充订单状态回调.
     * @author ymzhang
     * @date 2022-07-03
     * @time 21:45
     */
    public function jcNotify(Request $request)
    {
        $supplierId = $request->param('supplierId');
        $info = BaseSupplier::find($supplierId);
        if (empty($info)) {
            return web_request([], false, 506, '供应商账号异常，请联系商务');
        }
        $params = $request->post();
        //验证sign
        $handler = new JingChongHandler();
        $result = $handler->sycNotify($params);
        if (!($result['status'] && $result['code'] == 200)) {
            return web_request([], false, 202, '参数错误或者签名验证失败');
        }
        unset($params['Sign']);
        if ($params['State'] == '101') {
            $status = 3;
        } else if ($params['State'] == '102') {
            $status = 5;
        } else {
            $status = 4;
        }
        $data = [
            'supplier_id' => $supplierId,
            'origin_id' => $params['OrderID'],
            'order_id' => $params['MerchantOrderID'],
            'status' => $status,
            'status_msg' => $params['StateInfo'],
        ];
        $handler = new JingChong();
        $handler->notify($data);
    }

    /**
     * 商品信息异步通知(主要是价格).
     * @author ymzhang
     * @date 2022-10-20
     * @time 10:00
     */
    public function yiqidaPriceSyn()
    {
        try {
            $params = file_get_contents('php://input');
            //$sign = input('sign');
            $productChannel = json_decode($params, true);
//            file_put_contents('price.txt',var_export($params,true),FILE_APPEND);
            //file_put_contents('price_params.txt',var_export(input(),true),FILE_APPEND);
            if (empty($params)) {
                $msg = web_request([], false, 506, '参数错误');
                $notify = new \app\model\Notify([
                    'params' => $productChannel,
                    'from' => '亿奇达单个商品调价',
                    'relation_no' => '',
                    'mark' => $msg,
                ]);
                $notify->save();
                return $msg;
            }
            //供应商暂无签名验证
            $supplier = (new YiQiDaHandler())->getSupplierInfo();
            //业务处理
            /**
             * @var CouponProductChannel $couponProductChannel
             * @var BaseSupplier $supplier
             */
            $couponProductChannel = CouponProductChannel::query()
                ->where('supplier_id', $supplier->id)
                ->where('origin_id', $productChannel['mainId'])->find();
            if (!$couponProductChannel) {
                return;
            }
            //只对接官方直充的，卡密类的不对接
            if ($productChannel['virtualDelivery'] != YiQiDaHandler::VIRTUALDELIVERY_ZC) {
                return;
            }
            //商品状态
            if ($productChannel['status'] != YiQiDaHandler::PRODUCT_STATUS_ACTIVE) {
                return;
            }

            //若advancetime是过去式那么说明当前advanceprice价格已经生效；
            //若advancetime是将来时说明当advanceprice价格还未生效，
            if (strtotime($productChannel['advanceTime']) <= time()) {
                return;
            }

            //调价前的价格和调价后的价格一致，不修改
            if ($productChannel['advancePrice'] == $productChannel['price']) {
                return;
            }

            //系统中的成本价调价后的价格一致，不修改
            if ($couponProductChannel->cost_price == yuan2fen($productChannel['advancePrice'])) {
                return;
            }
            //将生效时间和生效价格保存起来
            $couponProductChannel->advance_price = yuan2fen($productChannel['advancePrice']);
            $couponProductChannel->advance_time = strtotime($productChannel['advanceTime']);
            if ($couponProductChannel->save())
            {
                Log::info('商品id:'. $couponProductChannel->id.',商品名称:'. $couponProductChannel->name.'被修改', $productChannel);
                $notify = new \app\model\Notify([
                    'params' => $productChannel,
                    'from' => '亿奇达单个商品调价',
                    'relation_no' => $couponProductChannel->supplier_id.$couponProductChannel->origin_id,
                    'mark' => ['msg' => '价格保存成功'],
                ]);
                $notify->save();
                return 'success';
            }
        }catch (\Exception $e) {
            Log::warning($e->getMessage());
        }
    }
}
